Micron Document




Python syntax and semantics
part 25/45 · 74.8 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Python has had support for lexical closures since version 2.2. Here's an example function that returns a function that approximates the derivative of the given function:

def derivative(f, dx):
"""Return a function that approximates the derivative of f
using an interval of dx, which should be appropriately small.
"""
def function(x):
return (f(x + dx) - f(x)) / dx
return function

Python's syntax, though, sometimes leads programmers of other languages to think that closures are not supported. Variable scope in Python is implicitly determined by the scope in which one assigns a value to the variable, unless scope is explicitly declared with global or nonlocal.cite-ref-26[22]

Note that the closure's binding of a name to some value is not mutable from within the function. Given:

>>> def foo(a, b):
... print(f'a: {a}')
... print(f'b: {b}')
... def bar(c):
... b = c
... print(f'b*: {b}')
... bar(a)
... print(f'b: {b}')
...
>>> foo(1, 2)
a: 1
b: 2
b*: 1
b: 2

──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────